﻿/********
* 
* 
*  Description:
*  Create By kain.hong at 9/13/2010 10:07:19 AM
*  
*
*  Revision History:
*  Date                  Who                 What
*  
* 
*/
#region namespace

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data.Objects;
using System.Data.Common;
using System.Data.EntityClient;
using Cherry.Agile.Data.DataAccess;

#endregion


namespace Cherry.Agile.Data.Repository
{
    /// <summary>
    /// 
    /// </summary>
    public sealed class ObjectContextWraper
    {

        static ThreadLocal<Dictionary<string, ObjectContext>> __local = new ThreadLocal<Dictionary<string, ObjectContext>>();

        internal ObjectContextWraper(DbConnection connection, string containerName)
        {
            if (__local.Value == null)
                __local.Value = new Dictionary<string, ObjectContext>();

            if (!__local.Value.ContainsKey(containerName))
            {
                var con = connection as EntityConnection;
                if (con == null)
                    throw new ArgumentException("invalid connection type");
                var context = new ObjectContext(con);
                __local.Value[containerName] = context;
                context.ContextOptions.LazyLoadingEnabled = false;
                context.ContextOptions.ProxyCreationEnabled = false;
                context.DefaultContainerName = containerName;
                con.Disposed += new EventHandler(Connection_Disposed);

            }

        }

        static void Connection_Disposed(object sender, EventArgs e)
        {
            var dict = __local.Value;
            foreach (var item in dict)
            {
                if (item.Value.Connection.Equals(sender))
                {
                    __local.Value.Remove(item.Key);

                    item.Value.Connection.Disposed -= new EventHandler(Connection_Disposed);
                    item.Value.Dispose();
                    break;
                }
            }
        }

        internal ObjectContext Reference(string contianer)
        {
            return __local.Value[contianer];
        }

    }
}
